﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OAclient.Models;
using System.Workflow.Activities;
using CommonLibrary.Common;
using ServiceApplication.Service.Basic;
using CommonLibrary.DataModel.Basic;
using ServiceApplication.Service.Plan;
using OAclient.Common;
using System.Data;
using System.Web.Security;
using ServiceApplication.Service.WorkFlow;
using System.IO;
using System.Web.UI.WebControls;
using System.Web.UI;
using OAclient.Filters;
using System.Configuration;

namespace OAclient.Controllers
{
    //[VaildateLogin]
    [ExceptionFilter]
    [LoggerFilter]
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        BasicService bs = new BasicService();
        PlanService ps = new PlanService();
        WorkFlowService wfs = new WorkFlowService();
        private const Int32 srchPageSize = 5;

        String storeUrl = ComVariable.StoreUrl;

        public ActionResult Main(UserModel user)
        {
            if (HttpContext.User.Identity.Name == "" || null == user.user)
                return RedirectToAction("LogOn", "Login");
            ViewData["usertree"] = ZTreeHelper.Serialize(bs.GetWebUserNodeList());
            ViewData["grouptree"] = Node.ConvertToZtree(ps.QueryGroupTreeByCreaterId(user.user.user_id));
            //System.Web.HttpContext.Current.Application
            //Dictionary<int, StateMachineWorkflowInstance> a = (Dictionary<int, StateMachineWorkflowInstance>)System.Web.HttpContext.Current.Application[MyWorkHelpr.WorkflowStaticTemplate];

            ViewData["login_name"] = user.user.user_name;
            ViewData["main_msgnum"] = getMsgCount(user);

            Session["fck_user_path"] = user.user.user_id.ToString();

            ////显示最新一条通知
            //var notifyEntity = ps.QueryLastNotify();
            //if (null != notifyEntity)
            //{
            //    ViewData["show_notifytitle"] = notifyEntity.notify_title;
            //    ViewData["show_notifycontent"] = notifyEntity.notify_content;
            //}
            //else
            //{
            //    ViewData["show_notifytitle"] = string.Empty;
            //    ViewData["show_notifycontent"] = string.Empty;
            //}
            //if (!String.IsNullOrEmpty(searchUrl))
            //{
            //    ViewData["searchUrl"] = searchUrl;
            //    ViewData["srchTabId"] = tabId;
            //}
            return View(user);
        }

        public ActionResult WorkArea(UserModel user)
        {
            //审批任务（待办，发起，完成）
            var dt_wfworking = wfs.QueryTask(user.user.user_id.ToString(), "未处理");
            if (dt_wfworking.Rows.Count > 10)
                dt_wfworking = dt_wfworking.AsEnumerable().Take(10).CopyToDataTable<DataRow>();
            ViewData["dt_wfworking"] = dt_wfworking;

            var dt_wfstart = wfs.queryIns(user.user.user_id.ToString());
            if (dt_wfstart.Rows.Count > 10)
                dt_wfstart = dt_wfstart.AsEnumerable().Take(10).CopyToDataTable<DataRow>();
            ViewData["dt_wfstart"] = dt_wfstart;

            var dt_wfworked = wfs.QueryTaskFinish(user.user.user_id.ToString(), "", "", "", "", "已处理");
            if (dt_wfworked.Rows.Count > 10)
                dt_wfworked = dt_wfworked.AsEnumerable().Take(10).CopyToDataTable<DataRow>();
            ViewData["dt_wfworked"] = dt_wfworked;

            //当前用户的委托审批
            var dt = wfs.QueryWfDelegByStrId(user.user.user_id);
            int[] wtrs = dt.AsEnumerable().Select(d => d.Field<int>("委托人编码")).ToArray();
            var dt_delegtask = wfs.QueryTaskByWtrIds(wtrs);
            ViewData["dt_delegtask"] = dt_delegtask;
            ViewData["user_id"] = user.user.user_id;
            return PartialView();
        }

        public ActionResult UserInfo(UserModel user)
        {

            UserEntity ue = bs.QueryUser(user.user.user_id);
            StaffEntity se = bs.QueryStaff(ue.staff_id);
            DeptEntity de = bs.QueryDept(se.dept_id);
            DutyEntity du = bs.QueryDuty(se.duty_id);
            ViewData["head_img"] = "true";
            ViewData["dept_name"] = de.dept_name;
            ViewData["duty_name"] = du.duty_name;
            ViewData["staff_erp"] = se.staff_erp;
            ViewData["staff_email"] = se.staff_email;

            return PartialView(ue);
        }

        public ActionResult UserSetting(UserModel user)
        {

            UserEntity ue = bs.QueryUser(user.user.user_id);
            StaffEntity staffEntity = bs.QueryStaff(ue.staff_id);

            ViewData["user_img"] = ue.user_img;
            DeptEntity de = bs.QueryDept(staffEntity.dept_id);
            DutyEntity du = bs.QueryDuty(staffEntity.duty_id);
            //ViewData["head_img"] = "true";
            //ViewData["dept_name"] = de.dept_name;
            //ViewData["duty_name"] = du.duty_name;

            String mail = staffEntity.staff_email;
            String mailfront = string.Empty;
            String mailback = string.Empty;
            if (mail == string.Empty)
            {
                mailfront = mail.Substring(0, mail.IndexOf('@'));
                mailback = mail.Substring(mail.IndexOf('@') + 1);
            }
            ViewData["staff_id"] = staffEntity.staff_id;
            //ViewData["staff_name"] = staffEntity.staff_name;
            ViewData["dept_id"] = staffEntity.dept_id;
            ViewData["dept_name"] = de.dept_name;
            ViewData["duty_id"] = staffEntity.duty_id;
            ViewData["duty_name"] = du.duty_name;
            ViewData["staff_sex"] = staffEntity.staff_sex;
            ViewData["staff_homeaddr"] = staffEntity.staff_homeaddr;
            ViewData["staff_img"] = staffEntity.staff_img;
            ViewData["staff_sfz"] = staffEntity.staff_sfz;
            ViewData["staff_postnum"] = staffEntity.staff_postnum;
            ViewData["staff_marrige"] = staffEntity.staff_marrige;
            ViewData["staff_study"] = staffEntity.staff_study;
            ViewData["staff_school"] = staffEntity.staff_school;
            ViewData["staff_major"] = staffEntity.staff_major;
            ViewData["staff_politics"] = staffEntity.staff_politics;
            ViewData["staff_birth"] = staffEntity.staff_birth;
            ViewData["staff_interest"] = staffEntity.staff_interest;
            ViewData["staff_zybl"] = staffEntity.staff_zybl;
            ViewData["staff_liveaddr"] = staffEntity.staff_liveaddr;
            ViewData["staff_livenum"] = staffEntity.staff_livenum;
            ViewData["staff_mobile"] = staffEntity.staff_mobile;
            ViewData["staff_shortnum"] = staffEntity.staff_shortnum;
            ViewData["staff_officenum"] = staffEntity.staff_officenum;
            ViewData["staff_officeaddr"] = staffEntity.staff_officeaddr;
            ViewData["staff_rzsj"] = staffEntity.staff_rzsj;
            ViewData["staff_lxr"] = staffEntity.staff_lxr;
            ViewData["staff_lxrphone"] = staffEntity.staff_lxrphone;
            ViewData["staff_jsr"] = staffEntity.staff_jsr;
            ViewData["staff_gzjl"] = staffEntity.staff_gzjl;
            ViewData["staff_jtcy"] = staffEntity.staff_jtcy;
            ViewData["staff_email"] = mailfront;
            ViewData["current_mail_domain"] = mailback;
            ViewData["staff_email_domain"] = domainSelect();
            ViewData["staff_qq"] = staffEntity.staff_qq;
            ViewData["staff_fax"] = staffEntity.staff_fax;
            ViewData["staff_height"] = staffEntity.staff_height;
            ViewData["staff_nation"] = staffEntity.staff_nation;
            ViewData["staff_sygz"] = staffEntity.staff_sygz;
            ViewData["staff_zzgz"] = staffEntity.staff_zzgz;
            ViewData["staff_sfsb"] = staffEntity.staff_sfsb;
            //ViewData["staff_code"] = staffEntity.staff_code;
            ViewData["staff_descn"] = staffEntity.staff_descn;
            ViewData["staff_ctime"] = staffEntity.staff_ctime;
            ViewData["staff_fjh"] = staffEntity.staff_fjh;
            ViewData["staff_erp"] = staffEntity.staff_erp;
            ViewData["staff_empsw"] = staffEntity.staff_empsw;
            ViewData["staff_kybz"] = staffEntity.staff_kybz;

            return PartialView();
        }

        public ActionResult UploadHeadImg(UserModel user)
        {

            //var path = Server.MapPath("~/");

            foreach (String upload in Request.Files)
            {
                if (Request.Files[upload] != null && Request.Files[upload].ContentLength > 0)
                {
                    var fileName = Request.Files[upload].FileName;
                    var fileExtend = fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower();
                    if (fileExtend == "bmp" || fileExtend == "jpg" || fileExtend == "gif")
                    {
                        var dirPath = storeUrl;
                        var filePath = Path.Combine("Person", Path.Combine(user.user.user_id.ToString(), "HeadImg"));
                        var savePath = Path.Combine(dirPath, filePath);
                        if (!Directory.Exists(savePath))
                            Directory.CreateDirectory(savePath);

                        filePath = Path.Combine(filePath, "HeadImg.jpg");

                        Request.Files[upload].SaveAs(Path.Combine(dirPath, filePath));
                        StaffEntity se = bs.QueryStaff(user.user.staff_id);
                        se.staff_img = filePath;
                        bs.UpdateStaff(se);
                        bs.UpdateHeadImg(user.user.user_id, filePath);
                        return Content("true");
                    }
                }
            }
            return Content("上传失败");
        }

        public ActionResult ChangePsw()
        {
            return PartialView();
        }



        #region 全局搜索

        public ActionResult GlobalSearch(UserModel user)
        {
            var searchText = Request.Form["searchText"];
            ViewData["searchText"] = searchText;

            var rowsCount = 0;

            var haveRecord = false;
            if (Request.Form["Message"].Contains("true"))
            {
                ViewData["sendMsg"] = this.switchSearchPage("sendMsg", 1, searchText, user, ref rowsCount);

                var sendMsgPageInfo = new PagingInfo
                {
                    CurrentPage = 1,
                    ItemsPerPage = srchPageSize,
                    TotalItems = rowsCount
                };
                ViewData["sendMsg_PageInfo"] = sendMsgPageInfo;

                if (rowsCount > 0)
                    haveRecord = true;

                ViewData["receiveMsg"] = this.switchSearchPage("receiveMsg", 1, searchText, user, ref  rowsCount);

                var receiveMsgPageInfo = new PagingInfo
                {
                    CurrentPage = 1,
                    ItemsPerPage = srchPageSize,
                    TotalItems = rowsCount
                };
                ViewData["receiveMsg_PageInfo"] = receiveMsgPageInfo;

                if (rowsCount > 0)
                    haveRecord = true;
            }
            if (Request.Form["wf_form"].Contains("true"))
            {
                ViewData["wfForm"] = this.switchSearchPage("wfForm", 1, searchText, user, ref  rowsCount);

                var wfFromPageInfo = new PagingInfo
                {
                    CurrentPage = 1,
                    ItemsPerPage = srchPageSize,
                    TotalItems = rowsCount
                };
                ViewData["wfFrom_PageInfo"] = wfFromPageInfo;

                if (rowsCount > 0)
                    haveRecord = true;
            }
            if (Request.Form["plan_notify"].Contains("true"))
            {
                ViewData["notify"] = this.switchSearchPage("notify", 1, searchText, user, ref  rowsCount);

                var notifyPageInfo = new PagingInfo
                {
                    CurrentPage = 1,
                    ItemsPerPage = srchPageSize,
                    TotalItems = rowsCount
                };
                ViewData["notify_PageInfo"] = notifyPageInfo;

                if (rowsCount > 0)
                    haveRecord = true;
            }
            if (Request.Form["wf_template"].Contains("true"))
            {
                ViewData["wfTemplate"] = this.switchSearchPage("wfTemplate", 1, searchText, user, ref  rowsCount);

                var wfTemplatePageInfo = new PagingInfo
                {
                    CurrentPage = 1,
                    ItemsPerPage = srchPageSize,
                    TotalItems = rowsCount
                };
                ViewData["wfTemplate_PageInfo"] = wfTemplatePageInfo;

                if (rowsCount > 0)
                    haveRecord = true;
            }
            if (Request.Form["wf_ins"].Contains("true"))
            {
                ViewData["wfIns"] = this.switchSearchPage("wfIns", 1, searchText, user, ref  rowsCount);

                var wfInsPageInfo = new PagingInfo
                {
                    CurrentPage = 1,
                    ItemsPerPage = srchPageSize,
                    TotalItems = rowsCount
                };
                ViewData["wfIns_PageInfo"] = wfInsPageInfo;

                if (rowsCount > 0)
                    haveRecord = true;
            }
            if (Request.Form["wf_task"].Contains("true"))
            {
                ViewData["wfTask"] = this.switchSearchPage("wfTask", 1, searchText, user, ref rowsCount);

                var wfTaskPageInfo = new PagingInfo
                {
                    CurrentPage = 1,
                    ItemsPerPage = srchPageSize,
                    TotalItems = rowsCount
                };
                ViewData["wfTask_PageInfo"] = wfTaskPageInfo;

                if (rowsCount > 0)
                    haveRecord = true;
            }
            if (!haveRecord)
                ViewData["noRecord"] = "没有您要搜索的内容";
            return View();
        }

        public ActionResult SwitchSearchPage(String srchBoundary, Int32 page, String searchText, UserModel user)
        {
            var rowsCount = 0;
            return Content(this.switchSearchPage(srchBoundary, page, searchText, user, ref rowsCount));
        }

        //public ActionResult RenderSearchResult(String searchUrl)
        //{
        //    //Message/MsgShowSelf?msg_id=11

        //    var ctrlName = searchUrl.Substring(1, searchUrl.IndexOf('/', 1));
        //    var actionName = searchUrl.Substring(ctrlName.Length, searchUrl.IndexOf('?'));
        //    var param = searchUrl.Substring(searchUrl.IndexOf('?') + 1);

        //    var paramName = param.Substring(0, param.IndexOf('='));
        //    var paramValue = param.Substring(paramName.Length);

        //    return RedirectToAction("MsgShowSelf", "Message", new { });
        //}

        private String switchSearchPage(String srchBoundary, Int32 page, String searchText, UserModel user, ref Int32 rowsCount)
        {
            String hyperlink = "#";
            var dtResult = new DataTable();
            switch (srchBoundary)
            {
                case "sendMsg":
                    dtResult = bs.QuerySendMsgForSearch(user.user.user_id.ToString(), searchText);
                    hyperlink = "3-2','/Message/MsgShowSelf?msg_id=";
                    srchBoundary = "已发信息";
                    break;
                case "receiveMsg":
                    dtResult = bs.QueryReceiveMsgForSearch(user.user.user_id.ToString(), searchText);
                    hyperlink = "3-3','/Message/MsgShow?msg_id=";
                    srchBoundary = "已收信息";
                    break;
                case "wfForm":
                    dtResult = bs.QueryFormListForSearch(user.user.user_id.ToString(), searchText);
                    hyperlink = "11-1','/Form/FormShow?form_id=";
                    srchBoundary = "表单";
                    break;
                case "notify":
                    dtResult = bs.QueryNotifyForSearch(user.user.user_id.ToString(), searchText);
                    hyperlink = "10-2','/Notify/NotifyModify?notify_id=";
                    srchBoundary = "公告";
                    break;
                case "wfTemplate":
                    dtResult = bs.QueryWfTemplateForSearch(user.user.user_id.ToString(), searchText);
                    hyperlink = "12-2','/Workflow/WFPlateShow?wftemplate_id=";
                    srchBoundary = "流程";
                    break;
                case "wfIns":
                    dtResult = bs.QueryWfInsForSearch(user.user.user_id.ToString(), searchText);
                    hyperlink = "#";
                    srchBoundary = "申请";
                    break;
                case "wfTask":
                    dtResult = bs.QueryWfTaskForSearch(user.user.user_id.ToString(), searchText);
                    hyperlink = "#";
                    srchBoundary = "审批";
                    break;
                default:
                    break;
            }
            rowsCount = dtResult.Rows.Count;
            if (dtResult.Rows.Count > 0)
                dtResult = dtResult.AsEnumerable().Skip((page - 1) * srchPageSize).Take(srchPageSize).CopyToDataTable<DataRow>();
            return this.produSearch(srchBoundary, hyperlink, dtResult);
        }

        private DataRow[] copyDataRow(DataTable origdt)
        {
            var dtRows = new DataRow[origdt.Rows.Count];
            origdt.Rows.CopyTo(dtRows, 0);
            return dtRows;
        }

        private String produSearch(String srchBoundary, String hyperlink, DataTable srchResult)
        {
            var rowCount = srchResult.Rows.Count;
            if (rowCount == 0)
                return String.Empty;

            HtmlTextWriter writer = new HtmlTextWriter(new StringWriter());
            writer.RenderBeginTag(HtmlTextWriterTag.H3);
            writer.Write(srchBoundary);
            writer.RenderEndTag();
            for (int rowIndex = 0; rowIndex < rowCount; rowIndex++)
            {
                // Div 当个记录结果
                writer.AddAttribute(HtmlTextWriterAttribute.Class, "scResult");
                writer.RenderBeginTag(HtmlTextWriterTag.Div);
                // head
                {
                    writer.AddAttribute(HtmlTextWriterAttribute.Class, "sc_header");
                    writer.RenderBeginTag(HtmlTextWriterTag.Div);
                    {
                        var param = "#";
                        var partLink = srchResult.Rows[rowIndex][0].ToString();

                        if (hyperlink != "#")
                            param = hyperlink + partLink;
                        writer.AddAttribute(HtmlTextWriterAttribute.Onclick, "search_render('" + param + "')");
                        writer.RenderBeginTag(HtmlTextWriterTag.A);
                        writer.Write(srchResult.Rows[rowIndex][1]);
                        writer.RenderEndTag();
                    }
                    writer.RenderEndTag();
                }
                // content
                {
                    writer.RenderBeginTag(HtmlTextWriterTag.Div);
                    writer.AddAttribute(HtmlTextWriterAttribute.Class, "cs_content");
                    {
                        writer.RenderBeginTag(HtmlTextWriterTag.Font);
                        {
                            var content = srchResult.Rows[rowIndex][3].ToString();
                            if (content.Length > 100)
                                content = content.Substring(0, 100) + "...";
                            writer.Write(content);
                        }
                        writer.RenderEndTag();
                    }
                    writer.RenderEndTag();
                }
                writer.RenderEndTag();
            }

            return writer.InnerWriter.ToString();
        }

        #endregion

        #region 未读消息查询

        public ActionResult getUnReadMsg(UserModel user)
        {
            //task
            var dtur_wftask = wfs.QueryTaskByRead(user.user.user_id.ToString(), 0);
            ViewData["dtur_wftask"] = dtur_wftask;

            //note
            var date = DateTime.Now.ToString("yyyy-MM-dd");
            var dtur_note = bs.GetNotesUtilCurrDay(date, user.user.user_id.ToString());
            ViewData["dtur_note"] = dtur_note;

            //msg
            var dtur_msg = bs.QueryMsgs(user.user.user_id, 0);
            ViewData["dtur_msg"] = dtur_msg;

            if ((dtur_wftask == null || dtur_wftask.Rows.Count == 0)
                && (dtur_note == null || dtur_note.Rows.Count == 0)
                && (dtur_msg == null || dtur_msg.Rows.Count == 0))
                return null;
            else
                return PartialView();
        }

        public ActionResult ShowMsg(UserModel user)
        {
            var result = new DataTable();
            result.Columns.Add("id");
            result.Columns.Add("name");
            result.Columns.Add("link");
            result.Columns.Add("update");
            result.Columns.Add("success");

            var dt = bs.QueryMsgs(user.user.user_id, 0);
            foreach (DataRow row in dt.Rows)
            {
                var newRow = result.NewRow();
                newRow["id"] = row["编码"];
                newRow["name"] = row["标题"];
                newRow["link"] = "/Message/MsgLittle?msg_id=" + row["编码"];
                newRow["update"] = "function(){}";
                newRow["success"] = "function(){}";
                result.Rows.Add(newRow);
            }

            dt = wfs.QueryTaskByRead(user.user.user_id.ToString(), 0);
            foreach (DataRow row in dt.Rows)
            {
                var newRow = result.NewRow();
                newRow["id"] = row["任务编码"];
                newRow["name"] = row["任务名称"];
                newRow["link"] = "/WorkFlow/WFProcess?uniqueid=" + row["实例标识"] + "&task_id=" + row["任务编码"] + "&ptask_id=" + row["父级编码"];
                newRow["update"] = "workarea-1-1-1-examine";
                newRow["success"] = "confirm_wf_msg('" + row["任务编码"] + "')";
                result.Rows.Add(newRow);
            }

            ViewData["msgs"] = result;
            if (result.Rows.Count == 0)
                return Content("NULL");
            return View();
        }

        public String getMsgCount(UserModel user)
        {
            if (user.user == null) return "";
            // 站内信
            var dt = bs.QueryMsgs(user.user.user_id, 0);
            var count = 0;
            if (dt != null)
                count += dt.Rows.Count;

            // 申请单
            dt = wfs.QueryTaskByRead(user.user.user_id.ToString(), 0);
            if (dt != null)
                count += dt.Rows.Count;

            var date = DateTime.Now.ToString("yyyy-MM-dd");
            var dtur_note = bs.GetNotesUtilCurrDay(date, user.user.user_id.ToString());
            if (dtur_note != null)
                count += dtur_note.Rows.Count;
            return count.ToString();
        }

        #endregion

        #region 公共方法

        public string DoChangePsw(UserModel user, string oldpsw, string newpsw)
        {
            if (user.user.user_psw != oldpsw)
            {
                return "原密码错误";
            }
            user.user.user_psw = newpsw;

            bs.UpdateUser(user.user);
            return "操作成功！";
        }

        public String DoMailChangePsw(UserModel user, String oldpsw, String newpsw)
        {
            var se = bs.QueryStaff(user.user.staff_id);
            //if (se.staff_empsw != oldpsw)
            //{
            //    return "原密码错误";
            //}
            se.staff_empsw = newpsw;
            bs.UpdateStaff(se);
            return "操作成功！";
        }

        public String DoUpdateUserInfo(UserModel user, String mailAccount)
        {
            var se = bs.QueryStaff(user.user.user_id);
            if (String.IsNullOrEmpty(mailAccount))
                return "账户不能为空";
            se.staff_email = mailAccount;
            bs.UpdateStaff(se);
            return "保存成功";
        }

        public ActionResult DoUserSetting(UserModel user)
        {
            StaffEntity staffEntity = bs.QueryStaff(user.user.staff_id);
            ////头像上传
            //var path = Server.MapPath("~/");
            //foreach (String upload in Request.Files)
            //{
            //    if (Request.Files[upload] != null && Request.Files[upload].ContentLength > 0)
            //    {
            //        var fileName = Request.Files[upload].FileName;
            //        var fileExtend = fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower();
            //        if (fileExtend == "bmp" || fileExtend == "jpg" || fileExtend == "gif")
            //        {
            //            var dirPath = Path.Combine(path, "webstore");
            //            dirPath = Path.Combine(dirPath, "Person");
            //            var filePath = Path.Combine(user.user.user_id.ToString(), "HeadImg");
            //            var savePath = Path.Combine(dirPath, filePath);
            //            if (!Directory.Exists(savePath))
            //                Directory.CreateDirectory(savePath);

            //            filePath = Path.Combine(filePath, "HeadImg.jpg");
            //            bs.UpdateHeadImg(user.user.user_id, filePath.Replace("\\", "/"));
            //            staffEntity.staff_img = filePath.Replace("\\", "/");
            //            Request.Files[upload].SaveAs(Path.Combine(dirPath, filePath));
            //        }
            //    }
            //}

            //staffEntity.staff_name = Request.Form["staff_name"].ToString();
            //staffEntity.dept_id = int.Parse(Request.Form["dept_id"].ToString());
            //staffEntity.duty_id = int.Parse(Request.Form["duty_id"].ToString());
            //staffEntity.staff_sex = Request.Form["staff_sex"].ToString();
            //staffEntity.staff_homeaddr = Request.Form["staff_homeaddr"].ToString();

            //staffEntity.staff_sfz = Request.Form["staff_sfz"].ToString();
            //staffEntity.staff_postnum = Request.Form["staff_postnum"].ToString();
            //staffEntity.staff_marrige = Request.Form["staff_marrige"].ToString();
            //staffEntity.staff_study = Request.Form["staff_study"].ToString();
            //staffEntity.staff_school = Request.Form["staff_school"].ToString();
            //staffEntity.staff_major = Request.Form["staff_major"].ToString();
            //staffEntity.staff_politics = Request.Form["staff_politics"].ToString();
            //staffEntity.staff_birth = Request.Form["staff_birth"].ToString();
            //staffEntity.staff_interest = Request.Form["staff_interest"].ToString();
            //staffEntity.staff_zybl = Request.Form["staff_zybl"].ToString();
            staffEntity.staff_liveaddr = Request.Form["staff_liveaddr"].ToString();
            staffEntity.staff_livenum = Request.Form["staff_livenum"].ToString();
            staffEntity.staff_mobile = Request.Form["staff_mobile"].ToString();
            staffEntity.staff_shortnum = Request.Form["staff_shortnum"].ToString();
            staffEntity.staff_officenum = Request.Form["staff_officenum"].ToString();
            //staffEntity.staff_rzsj = Request.Form["staff_rzsj"].ToString();
            //staffEntity.staff_lxr = Request.Form["staff_lxr"].ToString();
            //staffEntity.staff_lxrphone = Request.Form["staff_lxrphone"].ToString();
            //staffEntity.staff_jsr = Request.Form["staff_jsr"].ToString();
            //staffEntity.staff_gzjl = Request.Form["staff_gzjl"].ToString();
            //staffEntity.staff_jtcy = Request.Form["staff_jtcy"].ToString();
            staffEntity.staff_email = Request.Form["staff_email"].ToString() + Request.Form["staff_email_domain"].ToString();
            staffEntity.staff_qq = Request.Form["staff_qq"].ToString();
            staffEntity.staff_fax = Request.Form["staff_fax"].ToString();
            //staffEntity.staff_height = Request.Form["staff_height"].ToString();
            //staffEntity.staff_nation = Request.Form["staff_nation"].ToString();
            //staffEntity.staff_sygz = decimal.Parse(Request.Form["staff_sygz"].ToString() == "" ? "0" : Request.Form["staff_sygz"].ToString());
            //staffEntity.staff_zzgz = decimal.Parse(Request.Form["staff_zzgz"].ToString() == "" ? "0" : Request.Form["staff_zzgz"].ToString());
            //staffEntity.staff_sfsb = Request.Form["staff_sfsb"].ToString();
            //staffEntity.staff_code = Request.Form["staff_code"].ToString();
            //staffEntity.staff_descn = Request.Form["staff_descn"].ToString();
            //staffEntity.staff_ctime = Request.Form["staff_ctime"].ToString();
            staffEntity.staff_officeaddr = Request.Form["staff_officeaddr"].ToString();
            staffEntity.staff_fjh = Request.Form["staff_fjh"].ToString();
            //staffEntity.staff_erp = Request.Form["staff_erp"].ToString();
            //staffEntity.staff_empsw = Request.Form["staff_empsw"].ToString();
            //staffEntity.staff_kybz = Request.Form["staff_kybz"].ToString();

            bs.UpdateStaff(staffEntity);
            return Json(new ResTag(true));
        }

        #region tree

        #region 老版本的，建议不要用

        public string getUserTree()
        {
            string s = ZTreeHelper.Serialize(bs.GetWebUserNodeList());
            return s;
        }
        public string getUserCheckTree()
        {
            TreeNode[] tns = bs.GetWebUserNodeList();
            foreach (TreeNode item in tns)
            {
                foreach (TreeNode item2 in item.ChildNodes)
                {
                    item2.ShowCheckBox = true;
                }
            }
            string s = ZTreeHelper.Serialize(tns);
            return s;
        }

        #endregion

        public string getGroupTree(int user_id)
        {
            return Node.ConvertToZtree(ps.QueryGroupTreeByCreaterId(user_id));
        }

        //type:all,person,share
        public ActionResult getFileTree(UserModel user, string type)
        {
            string userfile_name = Server.MapPath("~/webstore/Person/" + user.user.user_id.ToString());
            string sharefile_name = Server.MapPath("~/webstore/Share/");
            var dt_myfile = bs.FilesQuery(user.user.user_id.ToString());
            var dt_share = bs.FilesQueryShare();
            var catalogs = dt_myfile.Select(x => x.file_catalog).Distinct().ToArray();
            var Folderlist = from q in catalogs
                             select new
                             {
                                 id = -1,
                                 name = q,
                                 nocheck = true,
                                 open = true,
                                 tag = "文件夹",
                                 children = from p in dt_myfile
                                            where p.file_catalog == q
                                            select new { id = p.file_id, name = p.file_name, nocheck = true, open = false, tag = "文件" }
                             };

            var ShareList = from p in dt_myfile
                            select new { id = p.file_id, name = p.file_name, nocheck = true, open = false, tag = "文件" };


            ////返回级数关系：我的文件-文件夹列表-文件列表
            var myztree = new { id = -1, name = "我的文件", open = true, nocheck = true, tag = "文件夹", children = Folderlist };
            var shareztree = new { id = -1, name = "共享文件", open = true, nocheck = true, tag = "文件夹", children = ShareList };
            var allztree = new { id = -1, name = "所有文件", open = true, nocheck = true, tag = "文件夹", children = new object[] { ShareList, shareztree } };
            if (string.IsNullOrEmpty(type) || type == "all")
            {
                return Json(allztree, JsonRequestBehavior.AllowGet);
            }
            else if (type == "person")
            {
                return Json(myztree, JsonRequestBehavior.AllowGet);
            }
            else if (type == "share")
            {
                return Json(shareztree, JsonRequestBehavior.AllowGet);
            }
            return null;
            //List<Node> nodelist = new List<Node>();
            //if (string.IsNullOrEmpty(type) || type == "all")
            //{
            //    nodelist.Add(FileHelper.GetFileTree(userfile_name, "我的文件", OAclient.Common.FileHelper.RelFileTag.personfiletag));
            //    nodelist.Add(FileHelper.GetFileTree(sharefile_name, "共享文件", OAclient.Common.FileHelper.RelFileTag.sharefiletag));
            //}
            //else if (type == "person")
            //{
            //    nodelist.Add(FileHelper.GetFileTree(userfile_name, "我的文件", OAclient.Common.FileHelper.RelFileTag.personfiletag));
            //}
            //else if (type == "share")
            //{
            //    nodelist.Add(FileHelper.GetFileTree(sharefile_name, "共享文件", OAclient.Common.FileHelper.RelFileTag.sharefiletag));
            //}

            //string res = Node.ConvertToZtree(nodelist);


            //return Json(ztree, JsonRequestBehavior.AllowGet);
        }

        public string getTxlTree(UserModel user)
        {
            List<Node> list = new List<Node>();
            var tree = bs.GetTxlTree(user.user.user_id, "我的通讯录");
            list.Add(tree);

            if (user.user.user_name != "admin")
            {
                var tree2 = bs.GetTxlTree(1, "共享通讯录");
                list.Add(tree2);
            }
            var tree3 = bs.GetTxlTreeYhList("公司员工");
            list.Add(tree3);
            string res = Node.ConvertToZtree(list);
            return res;
        }

        //职位->用户 选择树
        public ActionResult getDutyUserCheckTree(bool? nocheck)
        {
            if (null == nocheck)
            {
                nocheck = false;//默认是有check的树
            }
            var dt_duty = bs.QueryAllDutys();
            var duty_ids = dt_duty.AsEnumerable().Select(x => x["职位编码"]).ToArray();
            var dt_user = bs.QueryAllUsers();
            dt_user = dt_user.Select("在职标志 = '在职' ").CopyToDataTable();
            var childtree = from q in duty_ids
                            select new
                            {
                                id = q,
                                name = dt_duty.AsEnumerable().Where(x => x["职位编码"].ToString() == q.ToString()).ToArray().First()["职位名称"].ToString(),
                                nocheck = nocheck,
                                open = false,
                                tag = "职位",
                                children = from p in dt_user.AsEnumerable()
                                           where p["职位编码"].ToString() == q.ToString()
                                           select new { id = p["员工编码"], name = p["员工名称"], nocheck = nocheck, open = false, tag = "员工" }
                            };
            var objtree = new { id = -1, name = "公司职位", nocheck = nocheck, open = true, children = childtree };
            return Json(objtree);
        }

        //部门->员工 树
        public ActionResult getDeptUserCheckTree(bool? nocheck)
        {
            if (null == nocheck)
            {
                nocheck = false;//默认是有check的树
            }
            var dt_dept = bs.QueryAllDepts();
            var duty_ids = dt_dept.AsEnumerable().Select(x => x["部门编码"]).ToArray();
            var dt_user = bs.QueryAllUsers();
            dt_user = dt_user.Select("在职标志 = '在职' ").CopyToDataTable();
            var childtree = from q in duty_ids
                            select new
                            {
                                id = q,
                                name = dt_dept.AsEnumerable().Where(x => x["部门编码"].ToString() == q.ToString()).ToArray().First()["部门名称"].ToString(),
                                nocheck = nocheck,
                                open = false,
                                tag = "部门",
                                children = from p in dt_user.AsEnumerable()
                                           where p["部门编码"].ToString() == q.ToString()
                                           select new { id = p["员工编码"], name = p["员工名称"], nocheck = nocheck, open = false, tag = "员工" }
                            };
            var objtree = new { id = -1, name = "公司部门", nocheck = nocheck, open = true, children = childtree };
            return Json(objtree);
        }

        public ActionResult getWfSpqxCheckTree(string nocheck)
        {
            if (string.IsNullOrEmpty(nocheck))
            {
                nocheck = "false";//默认是没有check的树
            }
            var dt_spqxAll = wfs.WfSpqxQueryAll(1);
            var childtree = from q in dt_spqxAll.AsEnumerable()
                            select new
                            {
                                id = q["编码"],
                                name = q["名称"],
                                nocheck = nocheck,
                                open = false,
                                tag = "",
                            };
            var objtree = new { id = -1, name = "审批权限", nocheck = nocheck, open = true, children = childtree };
            return Json(objtree);
        }


        #endregion

        #region autobind

        //动态绑定 数据源 拼音选择用户列表
        public ActionResult SearchUserFormAll(string keyword)
        {
            //int[] wtrs = dt.AsEnumerable().Select(d => d.Field<int>("deleg_id")).ToArray();
            var dt = bs.QueryAllUsers();
            var res = from tmp in dt.AsEnumerable()
                      where GetSpelling.GetPYStr(tmp.Field<string>("用户名称").Replace(" ", "")).Contains(keyword)
                      select new { text = tmp.Field<string>("用户名称") + " " + tmp.Field<string>("部门名称") + " " + tmp.Field<string>("职位名称"), value = tmp.Field<int>("用户编码") };

            return Json(res, JsonRequestBehavior.AllowGet);
        }

        //动态绑定 数据源 根据用户ID返回最近外出的地点
        public ActionResult SearchStaffOutAddr(string keyword, UserModel user)
        {
            var dt = bs.QueryStaffTopTenAddr(user.user.user_id);

            if (keyword == null)
            {
                keyword = "";
            }
            var res = from tmp in dt.AsEnumerable()
                      where tmp.Field<string>("外出地点").Replace(" ", "").Contains(keyword)
                      select new { text = tmp.Field<string>("外出地点") + " " + tmp.Field<string>("联系人") + " " + tmp.Field<string>("电话"), value = tmp.Field<int>("登记号") };

            return Json(res, JsonRequestBehavior.AllowGet);
        }

        public ActionResult SearchStaffFormAll(string keyword)
        {
            //int[] wtrs = dt.AsEnumerable().Select(d => d.Field<int>("deleg_id")).ToArray();
            var dt = bs.QueryAllStaff();
            var res = from tmp in dt.AsEnumerable()
                      where GetSpelling.GetPYStr(tmp.Field<string>("员工名称").Replace(" ", "")).Contains(keyword)
                      select new { text = tmp.Field<string>("员工名称") + " " + tmp.Field<string>("部门名称") + " " + tmp.Field<string>("职位名称"), value = tmp.Field<int>("员工编码") };

            return Json(res, JsonRequestBehavior.AllowGet);
        }

        public ActionResult SearchTxlFormMy(string keyword, UserModel user)
        {
            //int[] wtrs = dt.AsEnumerable().Select(d => d.Field<int>("deleg_id")).ToArray();
            var dt = bs.QueryTxlByUserId(user.user.user_id);
            var res = from tmp in dt.AsEnumerable()
                      where GetSpelling.GetPYStr(tmp.Field<string>("名称").Replace(" ", "")).Contains(keyword)
                      select new { text = tmp.Field<string>("名称") + " " + tmp.Field<string>("小组名称"), value = tmp.Field<int>("编号") };

            return Json(res, JsonRequestBehavior.AllowGet);
        }

        public ActionResult SearchUserFormDept(string keyword, UserModel user)
        {
            //int[] wtrs = dt.AsEnumerable().Select(d => d.Field<int>("deleg_id")).ToArray();
            var dt = bs.QueryAllUsers();
            var res = from tmp in dt.AsEnumerable()
                      where GetSpelling.GetPYStr(tmp.Field<string>("用户名称").Replace(" ", "")).Contains(keyword)
                      select new { text = tmp.Field<string>("用户名称") + " " + tmp.Field<string>("部门名称") + " " + tmp.Field<string>("职位名称"), value = tmp.Field<int>("用户编码") };

            return Json(res, JsonRequestBehavior.AllowGet);
        }

        #endregion

        public string getMsg(UserModel user)
        {
            var dt = bs.QueryMsgs(user.user.user_id, 0);
            var msgs = String.Empty;

            //foreach (DataRow row in dt.Rows)//"&nbsp<a onclick='openMsgShow(" + row["编码"].ToString() + ")' >查看</a><br />";
            //    msgs += row["标题"].ToString() + "&nbsp<a onclick=\\'openMsgShow(" + row["编码"].ToString() + ")\\'>查看</a>";
            if (dt.Rows.Count == 0) return string.Empty;
            return dt.Rows[0]["编码"].ToString();
        }

        /// <summary>
        ///  修改在线人数根据时间
        /// </summary>z
        /// <param name="user"></param>
        public void UpdateLoginTime(UserModel user)
        {
            var loginTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            bs.UpdateLoginTime(user.user.user_id.ToString(), loginTime);
        }

        /// <summary>
        ///  计算在线人数
        /// </summary>
        /// <returns></returns>
        public ActionResult PersonCount()
        {
            var perCount = bs.QueryUserCount();
            return Content(perCount);
        }

        private List<SelectListItem> domainSelect()
        {
            List<SelectListItem> list = new List<SelectListItem>(){
                new SelectListItem{
                    Text = "@163.com",
                    Value ="@163.com"
                }
            };
            return list;
        }

        #endregion

        #region 全局配置

        public ActionResult GlobalConfig()
        {
            var config = bs.GetConfigs();
            ConfigModel configModel = new ConfigModel(config[ComVariable.ProviderName], config[ComVariable.ReadedName], config[ComVariable.LastDayName]);

            return View(configModel);
        }

        public ActionResult UpdateConfig()
        {
            var provider = Request.Form[ComVariable.ProviderName];
            var readed = Request.Form[ComVariable.ReadedName];
            var lastDay = Request.Form[ComVariable.LastDayName];
            for (int index = 0; index < 3; index++)
            {
                bs.UpdateValue(ComVariable.ProviderName, provider);
                bs.UpdateValue(ComVariable.ReadedName, readed);
                bs.UpdateValue(ComVariable.LastDayName, lastDay);
            }

            return RedirectToAction("GlobalConfig");
        }

        #endregion
    }
}
